import axios from "axios";
import {getToken, removeToken} from "./auth";
import {useUserStore} from "@/stores/user_store.js";

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const service = axios.create({
    baseURL: "/api",
    timeout: 5000
})

/**
 * 请求拦截器
 */
service.interceptors.request.use(config => {
    // 请求头携带token
    if (getToken()) {
        config.headers.set('An-Authorization', getToken())
    }

    // get请求映射params参数
    if (config.method === 'get' && config.params) {
        let url = config.url + '?' + tansParams(config.params);
        url = url.slice(0, -1);
        config.params = {};
        config.url = url;
    }
    if (config.method === 'post' || config.method === 'put') {
        const requestObj = {
            url: config.url,
            data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
            time: new Date().getTime()
        }
        const requestSize = Object.keys(JSON.stringify(requestObj)).length; // 请求数据大小
        const limitSize = 5 * 1024 * 1024; // 限制存放数据5M
        if (requestSize >= limitSize) {
            console.warn(`[${config.url}]: ` + '请求数据大小超出允许的5M限制，无法进行防重复提交验证。')
            return config;
        }
    }
    return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

/**
 * 响应拦截器
 */
service.interceptors.response.use(res => {
        // 未设置状态码则默认成功状态
        const code = res.data.code || 200

        // 获取错误信息
        const msg = res.data.msg

        // 二进制数据则直接返回
        if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
            return res.data
        }

        // 处理响应码
        if (code === 401) {
            return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
        } else if (code === 500) {
            return Promise.reject(new Error("服务器繁忙，请稍后重试！"))
        } else if (code === 601) {
            return Promise.reject(new Error(msg))
        } else if (code !== 200) {
            return Promise.reject('error')
        } else {
            return Promise.resolve(res.data)
        }
    },
    error => {
        // 打印错误信息
        console.log('err' + error)

        // 获取错误信息
        let {message} = error;

        // 匹配错误消息
        if (message.includes('401')) {
            message = '登录信息已过期 请重新登录'
        } else if (message.includes('500')) {
            message = "服务器繁忙，请稍后重试！"
        } else if (message.includes("Network Error")) {
            message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substr(message.length - 3) + "异常";
        }

        // 将用户登录信息删除
        const userStore = useUserStore()
        const {clearUserInfo} = userStore
        clearUserInfo()
        removeToken()

        error.message = message
        return Promise.reject(error)
    }
)

/**
 * 参数处理
 */
export function tansParams(params) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && value !== "" && typeof (value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&";
            }
        }
    }
    return result
}

export default service
